package wnhz.com.business.shareshop.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.util.LogUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import wnhz.com.business.LoginActivity;
import wnhz.com.business.MyApplication;
import wnhz.com.business.R;
import wnhz.com.business.base.BaseRVAdapter;
import wnhz.com.business.base.BaseViewHolder;
import wnhz.com.business.base.MyBaseActivity;
import wnhz.com.business.base.MyBaseFragment;
import wnhz.com.business.constants.Constants;
import wnhz.com.business.impl.ActionBarClickListener;
import wnhz.com.business.shareshop.activity.home.ConfirmOrderActivityS;
import wnhz.com.business.shareshop.bean.ShoppingCartListBean;
import wnhz.com.business.uitls.BroadCastReceiverUtil;
import wnhz.com.business.uitls.CommonUtils;
import wnhz.com.business.uitls.LogUtils;
import wnhz.com.business.uitls.MyCallBack;
import wnhz.com.business.uitls.Prefer;
import wnhz.com.business.uitls.ToastUtils;
import wnhz.com.business.uitls.Url;
import wnhz.com.business.uitls.XUtil;
import wnhz.com.business.view.CircleImageView;
import wnhz.com.business.view.TranslucentActionBar;

/**
 * function:  共享商城的购物车
 * author:   Administrator
 * date:     2018-01-24 0024
 */

public class ShareShopingCarFragment extends MyBaseFragment implements ActionBarClickListener {
    @BindView(R.id.rv_shoppingcart_goods)
    RecyclerView rvShoppingcartGoods;
    @BindView(R.id.checkbox_all)
    CheckBox checkbox_all;
    @BindView(R.id.tv_quanxuan)
    TextView tvQuanxuan;
    @BindView(R.id.tv_txt)
    TextView tvTxt;
    @BindView(R.id.tv_number)
    TextView tvNumber;
    @BindView(R.id.tv_makepay)
    TextView tvMakepay;
    Unbinder unbinder;
    private MyBaseActivity activity;

    @BindView(R.id.actionbar) //顶部标题
    TranslucentActionBar actionbar;
    private List<ShoppingCartListBean.InfoBean> itemdata = new ArrayList<>();
    private Boolean compile = true;
    private int chooseStoreNum = 0;//已选中商店的个数
    private double totalMoney = 0.00;//总价
    private BaseRVAdapter adapter_car;

    @Override
    protected void handleMsg(Message msg) {

    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_shopping_cart, container, false);
        ButterKnife.bind(this, view);
        activity = (MyBaseActivity) getActivity();
        actionbar.setData("购物车", 0, null, 0, "编辑", 0, this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            actionbar.setStatusBarHeight(getStatusBarHeight());
        }

//        initview();
        loadData();
        return view;
    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

//    private void initview() {
//        rvShoppingcartGoods.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
//        tvMakepay.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                String carIds="";
//                for (int i = 0; i < itemdata.size(); i++) {
//                    if (itemdata.get(i).isChecked()){
//                        chooseStoreNum = i;
//                        totalMoney = Double.parseDouble(itemdata.get(i).getPrice()) + totalMoney;
//                        tvNumber.setText("¥ " + totalMoney);
//                        carIds+="-"+itemdata.get(i).getCartid();
//                    }
//                }
//                if (TextUtils.isEmpty(carIds)){
//                    activity.MyToast("请选择商品");
//                }else {
//                    startActivity(ConfirmOrderActivityS.createIntent(activity, carIds+"-"));
//                }
//            }
//        });
//
//        checkbox_all.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                if (itemdata.size()>0){
//                    for (int i = 0; i < itemdata.size(); i++) {
//                        itemdata.get(i).setChecked(isChecked);
//                        for (int i1 = 0; i1 < itemdata.size(); i1++) {
//                            itemdata.get(i).setChecked(isChecked);
//                        }
//                    }
//                    if (adapter_car != null) {
//                        adapter_car.notifyDataSetChanged();
//                    }
//                }
//                jisuanPrice();
//                initRecycler();
//            }
//        });
//    }
//
//    private void initRecycler() {
//        rvShoppingcartGoods.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
//        adapter_car = new BaseRVAdapter(activity, itemdata) {
//            @Override
//            public int getLayoutId(int viewType) {
//                return R.layout.item_shopcar;
//            }
//
//            @Override
//            public void onBind(BaseViewHolder holder, final int position) {
//                String storename = itemdata.get(position).getGoods_name();//商店的名字
//                if (!TextUtils.isEmpty(storename)) {
//                    holder.setTextView(R.id.tv_shopname, storename);
//                }
//                holder.getView(R.id.tv_shopname).setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
////                        startActivity(GoodsStoreActivity.createIntent(ShopCarActivity.this,"1"));
//                    }
//                });
//                holder.getView(R.id.tv_lingquan).setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
////                        startActivity(LingQuanActivity.createIntent(ShopCarActivity.this,"1"));
//                    }
//                });
//                final CheckBox isCheckStore = holder.getView(R.id.cb_checkstore);
//                isCheckStore.setChecked(itemdata.get(position).isChecked());
//
//                isCheckStore.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        LogUtil.e(isCheckStore.isChecked() + "----" + position);
//                        itemdata.get(position).setChecked(!itemdata.get(position).isChecked());
//                        for (int i = 0; i < itemdata.size(); i++) {
//                            itemdata.get(position).setChecked(itemdata.get(position).isChecked());
//                        }
//                        boolean isAllChecked=true;
//                        for (int i = 0; i < itemdata.size(); i++) {
//
//                            if (!itemdata.get(i).isChecked()){
//                                isAllChecked=false;
//                            }
//                        }
//                        LogUtil.e(isCheckStore.isChecked() + "----" + isAllChecked);
//                        checkbox_all.setChecked(isAllChecked);
//                        jisuanPrice();//计算总价
//                        notifyDataSetChanged();
//                    }
//                });
//                RecyclerView recyclerView = holder.getView(R.id.recycler_inner);
//                recyclerView.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false));
//                final List<ShoppingCartListBean.InfoBean> goodslist = itemdata;
//                recyclerView.setAdapter(new BaseRVAdapter(activity, goodslist) {
//
//                    @Override
//                    public int getLayoutId(int viewType) {
//                        return R.layout.item_shopcar_inner;
//                    }
//
//                    @Override
//                    public void onBind(final BaseViewHolder holder, final int position1) {
//                        ImageView circleImageView = holder.getImageView(R.id.img_pic);//holder.getImageView(R.id.img_pic)
//                        if (!TextUtils.isEmpty(goodslist.get(position1).getLogo_pic())){
//
//                            Glide.with(activity).load(goodslist.get(position1).getLogo_pic()).error(R.drawable.ic_home_like).into(circleImageView);
//                        }
//                        holder.setTextView(R.id.tv_goods_name, goodslist.get(position1).getGoods_name());
//                        holder.setTextView(R.id.tv_goods_sku, goodslist.get(position1).getSkuinfo());
////                        final String limitbuy = goodslist.get(position1).getLimitbuy();
////                        if ("1".equals(goodslist.get(position1).getIsactivity())){//秒杀商品
////                            holder.getTextView(R.id.tv_goodstype).setText("秒杀");
////                            holder.getTextView(R.id.tv_goodstype).setVisibility(View.VISIBLE);
////                            holder.getView(R.id.ll_daojishi).setVisibility(View.VISIBLE);
////                            TimeViewComm8 timeViewComm8 = (TimeViewComm8) holder.getView(R.id.timeViewComm);
////                            String time = goodslist.get(position1).getDownTime();
////                            if (time != null) {
////                                String[] split = time.split(":");
////                                if (split.length==3){
////                                    timeViewComm8.startTime(Integer.parseInt(split[0]),Integer.parseInt(split[1]),Integer.parseInt(split[2]));
////                                }
////                            }
////                            if (!TextUtils.isEmpty(limitbuy)&&!TextUtils.equals(limitbuy,"0")){
////                                holder.setTextView(R.id.tv_limit,"最多可买"+limitbuy+"件");
////                            }
////                        }else {
//                            holder.getView(R.id.ll_daojishi).setVisibility(View.GONE);
//                            holder.getTextView(R.id.tv_goodstype).setVisibility(View.GONE);
////                        }
//                        String price = goodslist.get(position1).getPrice();
////                        String jifen = goodslist.get(position1).getIntegralprice();
//                        holder.setTextView(R.id.tv_price, price);
//                        holder.setTextView(R.id.tv_num, goodslist.get(position1).getNum());
//                        holder.getView(R.id.img_jian).setOnClickListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                if (Integer.parseInt(goodslist.get(position1).getNum()) >= 2) {
//                                    changeGoodsNum(position,position1,goodslist.get(position1).getCartid(), Integer.parseInt(goodslist.get(position1).getNum()) - 1);
//                                } else {
//                                    activity.MyToast("不能再减了");
//                                }
//                            }
//                        });
//
//                        holder.getView(R.id.img_add).setOnClickListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
////                                if ("1".equals(goodslist.get(position1).getIsactivity())&&!TextUtils.isEmpty(limitbuy)&&!TextUtils.equals(limitbuy,"0")){
////                                    if (Integer.parseInt(goodslist.get(position1).getNum()) < Integer.parseInt(limitbuy)){
////                                        changeGoodsNum(position,position1,goodslist.get(position1).getCartid(), Integer.parseInt(goodslist.get(position1).getNum()) + 1);
////                                    }else {
////                                        MyToast("最多购买"+limitbuy+"件");
////                                    }
////                                }else {
//                                    changeGoodsNum(position,position1,goodslist.get(position1).getCartid(), Integer.parseInt(goodslist.get(position1).getNum()) + 1);
////                                }
//                            }
//                        });
//                        CheckBox isCheckGoods = holder.getView(R.id.cb_checkgoods);
//                        isCheckGoods.setChecked(goodslist.get(position1).isChecked());
//                        isCheckGoods.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//                            @Override
//                            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                                LogUtil.e(isChecked + "----" + position);
//                                goodslist.get(position1).setChecked(isChecked);
//                                boolean isStoreAllGoodsCheaked=true;
//                                for (int i = 0; i < itemdata.size(); i++) {
//                                    if (!itemdata.get(i).isChecked()){
//                                        isStoreAllGoodsCheaked =false;
//                                    }
//                                }
//                                LogUtil.e(isChecked + "----" + position+"--"+ isStoreAllGoodsCheaked);
//                                itemdata.get(position).setChecked(isStoreAllGoodsCheaked);
//                                jisuanPrice();//计算总价
//                                adapter_car.notifyDataSetChanged();
//                            }
//                        });
//                        holder.getView(R.id.ll_item).setOnLongClickListener(new View.OnLongClickListener() {
//                            @Override
//                            public boolean onLongClick(View v) {
//                                new AlertDialog.Builder(activity).setTitle("删除该商品?").setPositiveButton("确认", new DialogInterface.OnClickListener() {
//                                    @Override
//                                    public void onClick(DialogInterface dialog, int which) {
//                                        deleteGoods(position,position1,goodslist.get(position1).getCartid());
//                                    }
//                                }).setNegativeButton("取消",null).create().show();
//
//                                return false;
//                            }
//                        });
//                    }
//                });
//            }
//        };
//        rvShoppingcartGoods.setAdapter(adapter_car);
//        adapter_car.notifyDataSetChanged();
//    }
//
//    private void jisuanPrice(){
//        double totalPrice=0.00;
//        int checkNum=0;
//        for (int i = 0; i < itemdata.size(); i++) {
//            List<ShoppingCartListBean.InfoBean> goodslist = itemdata;
//            for (int i1 = 0; i1 < goodslist.size(); i1++) {
//                if (goodslist.get(i1).isChecked()){
//                    totalPrice+=Double.parseDouble(goodslist.get(i1).getPrice())*Double.parseDouble(goodslist.get(i1).getNum());
//                    checkNum++;
//                }
//            }
//        }
//        tvNumber.setText( CommonUtils.doubleToString(totalPrice)+"");
//
//        tvMakepay.setText("结算（"+ checkNum+"）");
//    }

    /**
     * 删除购物车
     *param token
     *param cartid
     */
    private void deleteGoods(final int storePosition, final int goodsPosition,String cartid) {
        Map<String, Object> map = new HashMap<>();
        if (!TextUtils.isEmpty(Prefer.getInstance().getToken())){
            map.put("token",  Prefer.getInstance().getToken());
        }else {
            activity.MyToast("请登录");
            startActivity(new Intent(activity,LoginActivity.class));
            activity.finish();
        }
        Set<String> set = map.keySet();
        for (String s : set) {
            LogUtil.e("删除购物车参数："+s+":"+map.get(s));
        }
        map.put("cartid", cartid);
        activity.showDialog("加载中...");}
//        XUtil.Post(Url.GOODSCART_DELCART,map,new MyCallBack<String>(){
//            @Override
//            public void onSuccess(String result) {
//                super.onSuccess(result);
//                LogUtil.e("----删除购物车----"+result);
//                try {
//                    JSONObject jsonObject = new JSONObject(result);
//                    String status =jsonObject.getString("result");
//                    String info  = jsonObject.getString("info");
//                    if ("1".equals(status)){
//                        activity.MyToast(info);
//                        BroadCastReceiverUtil.sendBroadcast(activity, Constants.ACTION_CHOOSE_GWC);//刷新购物车数量小红点
//                        itemdata.get(storePosition).remove(goodsPosition);
//                        if (beanList.get(storePosition).getGoodslist().size()==0){
//                            beanList.remove(storePosition);
//                        }
//                        jisuanPrice();
//                        adapter_car.notifyDataSetChanged();
////                        loadGoodsList();
//                    }else{
//                        MyToast(info);
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//
//            @Override
//            public void onError(Throwable ex, boolean isOnCallback) {
//                super.onError(ex, isOnCallback);
//                closeDialog();
//            }
//
//            @Override
//            public void onFinished() {
//                super.onFinished();
//                closeDialog();
//            }
////        });
//    }

    /**
     * 修改购物车
     * param token
     */
    private void changeGoodsNum(final int storePosition, final int goodsPosition, String cartid, final int num){

        Map<String, Object> map = new HashMap<>();
        if (!TextUtils.isEmpty(Prefer.getInstance().getToken())){
            map.put("token",  Prefer.getInstance().getToken());
        }else {
            ToastUtils.showToast(activity,"请登录");
            startActivity(new Intent(activity,LoginActivity.class));
            activity.finish();
        }
        Set<String> set = map.keySet();
        for (String s : set) {
            LogUtil.e("修改购物车参数："+s+":"+map.get(s));
        }
        map.put("cartid", cartid);
        map.put("nums", num);
        activity.showDialog("加载中...");
//        XUtil.Post(Url.GOODSCART_CHANGENUMCART,map,new MyCallBack<String>(){
//            @Override
//            public void onSuccess(String result) {
//                super.onSuccess(result);
//                LogUtil.e("----修改购物车----"+result);
//                try {
//                    JSONObject jsonObject = new JSONObject(result);
//                    String status =jsonObject.getString("result");
//                    String info  = jsonObject.getString("info");
//                    if ("1".equals(status)){
//                        MyToast(info);
//                        beanList.get(storePosition).getGoodslist().get(goodsPosition).setNum(num+"");
//                        adapter_car.notifyDataSetChanged();
//                        jisuanPrice();
////                        loadGoodsList();
//                    }else{
//                        MyToast(info);
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//
//            @Override
//            public void onError(Throwable ex, boolean isOnCallback) {
//                super.onError(ex, isOnCallback);
//                closeDialog();
//            }
//
//            @Override
//            public void onFinished() {
//                super.onFinished();
//                closeDialog();
//            }
//        });

    }

    private void loadData() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getToken());
        XUtil.Post(Url.CART_CARTLIST, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                LogUtils.e("----------------", "---------------" + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String re = jsonObject.optString("re");
                    if (re.equals("1")) {
                        Gson gson = new Gson();
                        ShoppingCartListBean shoppingCartListBean = gson.fromJson(result, ShoppingCartListBean.class);
                        itemdata = shoppingCartListBean.getInfo();
//                        initRecycler();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }




    @Override
    public void onLeftClick() {

    }

    @Override
    public void onRightClick() {

    }

    @Override
    public void onEditTextClick() {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
